package cn.wgx.modules.sys.util;

import cn.wgx.commons.security.shiro.realm.CustomRealm;
import cn.wgx.commons.util.BaseLogger;
import cn.wgx.commons.util.SpringContextHolder;
import cn.wgx.modules.sys.entity.SysPermission;
import cn.wgx.modules.sys.entity.SysRole;
import cn.wgx.modules.sys.entity.SysUser;
import cn.wgx.modules.sys.services.SysDutyService;
import cn.wgx.modules.sys.services.SysPermissionService;
import cn.wgx.modules.sys.services.SysRoleService;
import com.google.common.collect.Lists;
import org.springframework.context.annotation.DependsOn;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static cn.wgx.modules.sys.util.UserUtil.getUserById;


@Component
@DependsOn(value = "springContextHolder")
public class PermissionUtil extends BaseLogger {

    private static String CACHE_NAME_ALLPERMISSION = "sysPermissionList";

    private static RedisTemplate redisTemplate;

    private static SysPermissionService sysPermissionService;

    private static SysRoleService sysRoleService;

    private static SysDutyService sysDutyService;

    static {
        sysPermissionService = SpringContextHolder.getBean("sysPermissionService");
        sysRoleService = SpringContextHolder.getBean("sysRoleService");
        sysDutyService = SpringContextHolder.getBean("sysDutyService");
        redisTemplate = SpringContextHolder.getBean("redisTemplate");
    }


    public static String getPerNameByUri(String uri, String method) {
        List<SysPermission> sysPermissionServiceList = getList();
        for (SysPermission sysPermission : sysPermissionServiceList) {
            if ("N".equals(sysPermission.getMenu_flag())
                    && sysPermission.getMethod().equals(method.toUpperCase())
                    && sysPermission.getUrl().equals(uri)) {
                return sysPermission.getPermissionName();
            }
        }
        return "未知";
    }

    public static CustomRealm.Principal iniRoleAndPermission(CustomRealm.Principal principal) {
//        CustomRealm.Principal principal = (CustomRealm.Principal)principals.getPrimaryPrincipal();
        List<SysRole> roles = principal.getSysRoles_list();
        List<SysPermission> permissions = principal.getSysPermissions_list();
        if (roles == null) {
            roles = PermissionUtil.getRoleByUserId(principal.getId());
        }
        if (permissions == null) {
            if(principal.getId().equals(1)){//如果用户ID为1,是超级管理员,则获取所有权限数据
                permissions = PermissionUtil.getList();
            }else{
                permissions = PermissionUtil.getPermissionByRoles(roles);//添加角色对应所有权限
                List<SysPermission> otherPermissionByUser = PermissionUtil.getOtherPermissionByUser(principal.getUser());//添加职责权限和个人特殊授权
                permissions = PermissionUtil.hebing(permissions, otherPermissionByUser);//合并重复权限
            }
        }
        principal.setSysRoles_list(roles);
        principal.setSysPermissions_list(permissions);

        return principal;
    }

    public static List<SysPermission> getList() {
        ValueOperations valueOperations = redisTemplate.opsForValue();
        Object sysPermissionList = valueOperations.get(CACHE_NAME_ALLPERMISSION);
        if (sysPermissionList == null) {
            List<SysPermission> sysPermissionServiceList = sysPermissionService.getList();
            valueOperations.set(CACHE_NAME_ALLPERMISSION, sysPermissionServiceList, 5 * 60, TimeUnit.SECONDS);
            return sysPermissionServiceList;
        }
        return (List<SysPermission>) sysPermissionList;
    }

    /**
     * 从数据库中获取用户所有权限信息
     *
     * @param
     * @return
     */
    public static List<SysPermission> getOtherPermissionByUser(SysUser sysUser) {
        List<SysPermission> permissionsByUserId = sysPermissionService.getPermissionsByUserId(sysUser.getUser_id());
        return permissionsByUserId;
    }

    public static List<SysPermission> hebing(List<SysPermission> list1, List<SysPermission> list2) {
        List<SysPermission> a = Lists.newArrayList();
        for (SysPermission sysPermission : list1) {
            boolean b = true;
            for (SysPermission sysPermission1 : list2) {
                if (sysPermission.getPermission_id().equals(sysPermission1.getPermission_id())) {
                    b = false;
                    break;
                }
            }
            if (b) {
                a.add(sysPermission);
            }
        }
        list2.addAll(a);
        return list2;
    }

    /**
     * 从数据库中获取角色信息
     *
     * @param
     * @return
     */
    public static List<SysRole> getRoleByUserId(Integer userId) {
        List<SysRole> sysRoleList = new ArrayList();
        if (userId != null) {
            SysUser sysUser = getUserById(userId);
            sysRoleList = sysRoleService.getRoleListBySysUser(sysUser);
        }
        return sysRoleList;
    }

    /**
     * 从数据库中获取权限信息
     *
     * @param
     * @return
     */
    public static List<SysPermission> getPermissionByRoles(List<SysRole> roles) {
        List<SysPermission> sysPermissions = new ArrayList<>();
        if (roles != null) {
            for (SysRole role : roles) {
                List<SysPermission> sysPermission = sysPermissionService.getPermissionsByRoleId(role.getRole_id());
                sysPermissions.addAll(sysPermission);
            }
        }
        return sysPermissions;
    }


}
